package com.mystudy.springcloud.service;

import com.mystudy.springcloud.dao.OrderDao;
import com.mystudy.springcloud.domain.Order;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class OrderService {
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private StorageService storageService;
	@Autowired
	private AccountService accountService;

	/**
	 * @功能: 创建订单 --> 调用库存服务减库存 --> 调用账户服务扣减余额 --> 修改订单状态
	 */
	@GlobalTransactional(name = "myTx", rollbackFor = Exception.class)
	public void createOrder(Order order) {
		if (order == null) {
			log.error("订单参数为空 - 订单创建失败");
		}
		log.info("---------------------> 1 - 开始新建订单 <---------------------");
		orderDao.createOrder(order);
		log.info("---------------------> 2 - 订单微服务开始调用库存做扣减 <---------------------");
		storageService.decrease(order.getProductId(), order.getCount());
		log.info("---------------------> 3 - 订单微服务开始调用账户做扣减 <---------------------");
		accountService.decrease(order.getUserId(), order.getMoney());
		log.info("---------------------> 4 - 修改订单的状态( 0 --> 1 ) <---------------------");
		orderDao.updateOrderStatue(order.getUserId(), 0);
		log.info("---------------------> 5 - 新建订单完成 <---------------------");
	}
}
